﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web;
using System.Web.Ria.Services;

namespace System.Web.Ria
{
    public class DomainServiceHostFactoryEx : DomainServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            // HTTP Request Url could be: http://www.silverlightweblog.com/ClientBin/Silverlight-Weblog-UI-Web-RiaServices-BlogDomainService.svc/binary
            // BaseAddress could be: http://silverlightweblog.com/ClientBin/Silverlight-Weblog-UI-Web-RiaServices-BlogDomainService.svc, 
            //                       http://www.silverlightweblog.com/ClientBin/Silverlight-Weblog-UI-Web-RiaServices-BlogDomainService.svc, 
            //                       http://silverlig27.web703.discountasp.net/ClientBin/Silverlight-Weblog-UI-Web-RiaServices-BlogDomainService.svc.
            return new DomainServiceHost(serviceType, FilterAddresses(baseAddresses));
        }

        private Uri GetBaseAddressForCurrentUrlRequest(Uri[] baseAddresses)
        {
            Uri RequestURI = HttpContext.Current.Request.Url;
            foreach (Uri baseAddress in baseAddresses)
            {
                if (RequestURI.ToString().StartsWith(baseAddress.ToString()))
                    return baseAddress;
            }
            throw new Exception(
            string.Format("Could not successfully route Request URL to BaseAddress. Request URL: {0} . Base Addresses: {1}"
                , RequestURI
                , String.Join(", ", baseAddresses.Select(u => u.ToString()).ToArray())));
        }

        private static Uri[] FilterAddresses(Uri[] baseAddresses)
        {
            return baseAddresses.GroupBy(uri => uri.Scheme).SelectMany(uri => uri).ToArray();
        }
    }
}
